package com.ruoyi.generator.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.ServiceConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.generator.domain.GenConfig;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.generator.domain.GeneratedRecords;
import com.ruoyi.generator.service.IGeneratedRecordsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 代码生产记录Controller
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@RestController
@RequestMapping("/generator/records")
public class GeneratedRecordsController extends BaseController
{
    @Autowired
    private IGeneratedRecordsService generatedRecordsService;

    @Autowired
    private ISysConfigService sysConfigService;


    /**
     * 生成代码
     */
    @PostMapping("/code")
    public void code(
            @RequestBody GenConfig genConfig
            , HttpServletResponse response) throws IOException {
        byte[] data = generatedRecordsService.generatorCode(genConfig.getTables(),genConfig.getId(),genConfig.getModel());
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 查看详情
     */
    @GetMapping(value = "/check/{id}")
    public AjaxResult check(@PathVariable("id") Long id)
    {
        //TODO 查看详情
        //查看状态 根据不同状态显示不同结果
        GeneratedRecords generatedRecords = generatedRecordsService.selectGeneratedRecordsById(id);

        if (generatedRecords!=null&& generatedRecords.getGenStatus()!=null){
            return generatedRecordsService.check(generatedRecords);
        }else {
            throw new ServiceException("错误！请联系管理员!");
        }

    }


    /**
     * 查询代码生产记录列表
     */
    @PreAuthorize("@ss.hasPermi('generator:records:list')")
    @GetMapping("/list")
    public TableDataInfo list(GeneratedRecords generatedRecords)
    {
        String s = sysConfigService.selectConfigByKey(ServiceConstants.GEN_CODE_RULE_MASTER);
        boolean b = SecurityUtils.hasRole(s);
        if (b){
            startPage();
            List<GeneratedRecords> list = generatedRecordsService.selectGeneratedRecordsList(generatedRecords);
            return getDataTable(list);
        }else {
            generatedRecords.setUserId(SecurityUtils.getUserId());
            startPage();
            List<GeneratedRecords> list = generatedRecordsService.selectGeneratedRecordsList(generatedRecords);
            return getDataTable(list);
        }
    }

    /**
     * 导出代码生产记录列表
     */
    @PreAuthorize("@ss.hasPermi('generator:records:export')")
    @Log(title = "代码生产记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GeneratedRecords generatedRecords)
    {
        List<GeneratedRecords> list = generatedRecordsService.selectGeneratedRecordsList(generatedRecords);
        ExcelUtil<GeneratedRecords> util = new ExcelUtil<GeneratedRecords>(GeneratedRecords.class);
        util.exportExcel(response, list, "代码生产记录数据");
    }

    /**
     * 获取代码生产记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('generator:records:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        return success(generatedRecordsService.selectGeneratedRecordsById(id));
    }

    /**
     * 提交审核
     */
    @PreAuthorize("@ss.hasPermi('generator:records:toExamine')")
    @GetMapping(value = "/toExamine/{id}")
    public AjaxResult toExamine(@PathVariable("id") Long id)
    {
        return success(generatedRecordsService.toExamine(id));
    }

    /**
     * 审核通过
     */
    @PreAuthorize("@ss.hasPermi('generator:records:examineSuccess')")
    @GetMapping(value = "/examineSuccess/{id}")
    public AjaxResult examineSuccess(@PathVariable("id") Long id)
    {
        return success(generatedRecordsService.examineSuccess(id));
    }


    /**
     * 驳回提交
     */
    @PreAuthorize("@ss.hasPermi('generator:records:toReject')")
    @GetMapping(value = "/toReject/{id}")
    public AjaxResult toReject(@PathVariable("id") Long id,String message)
    {
        return success(generatedRecordsService.toReject(id,message));
    }



    /**
     * 提交测试（新增）
     */
    @PreAuthorize("@ss.hasPermi('generator:records:test')")
    @Log(title = "代码生产记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GeneratedRecords generatedRecords)
    {
        return toAjax(generatedRecordsService.testGeneratedRecords(generatedRecords));
    }

    /**
     * 保存草稿
     */
    @PreAuthorize("@ss.hasPermi('generator:records:draft')")
    @Log(title = "保存草稿", businessType = BusinessType.INSERT)
    @PostMapping("/saveDraft")
    public AjaxResult saveDraft(@RequestBody GeneratedRecords generatedRecords)
    {
        generatedRecords.setGenStatus(ServiceConstants.GEN_STATIC_DRAFT);//保存为草稿状态
        generatedRecords.setGenStatusInfo("草稿状态未提交！");//保存为草稿状态
        generatedRecords.setUserId(SecurityUtils.getUserId());
        if (generatedRecords.getId()!=null){
            return toAjax(generatedRecordsService.updateGeneratedRecords(generatedRecords));
        }
        return toAjax(generatedRecordsService.insertGeneratedRecords(generatedRecords));
    }

    /**
     * 提交测试（修改）
     */
    @PreAuthorize("@ss.hasPermi('generator:records:test')")
    @Log(title = "代码生产记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GeneratedRecords generatedRecords)
    {
        return toAjax(generatedRecordsService.testGeneratedRecords(generatedRecords));
    }



    /**
     * 删除代码生产记录
     */
    @PreAuthorize("@ss.hasPermi('generator:records:remove')")
    @Log(title = "代码生产记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(generatedRecordsService.deleteGeneratedRecordsByIds(ids));
    }
}
